package com.group.nepg.controller;

import com.group.common.users.NEPGUser;
import com.group.common.utils.DataGenerator;
import com.group.common.utils.MyUtils;
import com.group.nepg.entity.AccurateAqiData;
import com.group.nepg.entity.AccurateAqiDataFactory;
import com.group.nepm.statisticDataManagement.entity.StatisticData;
import com.group.neps.entity.RowAqiData;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.function.UnaryOperator;


 //测量数据控制器 - 处理空气质量测量数据的采集与提交
 //负责显示公众反馈详情，并收集网格员的专业测量数据

public class MeasurementController {
    // FXML 控件绑定
    @FXML
    private Label username;
    @FXML
    private Label phoneNumber;
    @FXML
    private Label province;
    @FXML
    private Label city;
    @FXML
    private Label address;
    @FXML
    private Label rowAqiData;
    @FXML
    private Label time;
    @FXML
    private Label remark;
    @FXML
    private TextField so2Field;
    @FXML
    private TextField coField;
    @FXML
    private TextField pm25Field;

    private static NEPGUser user;
    private static ArrayList<StatisticData> statisticDataList = MyUtils.readFileToArrayList("group/data/statistic_data_arraylist.dat");
    public static RowAqiData selectedRowAqiData =  null;
    public static boolean isCommit = false;

    // 测量值范围限制
    private static final double SO2_MIN = 0.0;
    private static final double SO2_MAX = 2500.0;
    private static final double CO_MIN = 0.0;
    private static final double CO_MAX = 150.0;
    private static final double PM25_MIN = 0.0;
    private static final double PM25_MAX = 500.0;

    // 数字格式验证正则表达式
    private static final Pattern NUMBER_PATTERN = Pattern.compile("^\\d*(\\.\\d{0,2})?$");

    // 用户信息访问器
    public static NEPGUser getUser() {
        return user;
    }

    public static void setUser(NEPGUser user) {
        MeasurementController.user = user;
    }


    //给页面加网格员背景
    @FXML
    private ImageView imageView;
    @FXML
    private AnchorPane root;

    @FXML
    public void initializeImage() {
        try {

            Image image = new Image(getClass().getResourceAsStream("../image/grid.png"));
            imageView.setImage(image);
            imageView.fitWidthProperty().bind(root.widthProperty());
            imageView.fitHeightProperty().bind(root.heightProperty());
            imageView.setPreserveRatio(false);
            imageView.setSmooth(true);
        } catch (Exception e) {
            System.err.println("加载图片失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void setSelectedRowAqiData(RowAqiData selectedRowAqiData) {
        MeasurementController.selectedRowAqiData = selectedRowAqiData;
    }


    //初始化方法

    public void initialize() {
        // 初始化图片
        initializeImage();

        // 验证必要数据已设置
        if (user == null || selectedRowAqiData == null) {
            showErrorAndExit("数据错误", "未找到用户或反馈数据，请重新登录");
            return;
        }

        try {
            // 初始化UI显示反馈详情
            username.setText(selectedRowAqiData.getUser().getUsername());
            phoneNumber.setText(selectedRowAqiData.getUser().getPhoneNumber());
            province.setText(selectedRowAqiData.getLocation().getProvince().getName());
            city.setText(selectedRowAqiData.getLocation().getCity().getName());
            address.setText(selectedRowAqiData.getLocation().getAddress());
            rowAqiData.setText("等级" + (selectedRowAqiData.getAqiLevel().ordinal() + 1));
            time.setText(selectedRowAqiData.getTime().toString());
            remark.setText(selectedRowAqiData.getRemark());

            // 设置输入验证
            setupInputValidation();

        } catch (Exception e) {
            e.printStackTrace();
            showErrorAndExit("初始化失败", "加载数据时发生错误，请重试");
        }
    }

    // 设置数据输入验证

    private void setupInputValidation() {
        // 设置SO2输入验证 (0-2500)
        so2Field.setTextFormatter(createNumberFormatter(SO2_MIN, SO2_MAX));

        // 设置CO输入验证 (0-150)
        coField.setTextFormatter(createNumberFormatter(CO_MIN, CO_MAX));

        // 设置PM2.5输入验证 (0-500)
        pm25Field.setTextFormatter(createNumberFormatter(PM25_MIN, PM25_MAX));
    }


    // 创建数字格式化器，限制范围和精度
    //不符合数字格式，或者超出范围，都无法输入。

    private TextFormatter<String> createNumberFormatter(double min, double max) {
        UnaryOperator<TextFormatter.Change> filter = change -> {
            String newText = change.getControlNewText();
            if (newText.isEmpty()) {
                return change; // 允许空值
            }

            // 验证数字格式
            if (!NUMBER_PATTERN.matcher(newText).matches()) {
                return null;
            }

            // 验证数值范围
            try {
                double value = Double.parseDouble(newText);
                if (value < min || value > max) {
                    return null; // 超出范围，拒绝修改
                }
            } catch (NumberFormatException e) {
                return null;
            }

            return change;
        };

        return new TextFormatter<>(filter);
    }


    // 提交所有测量数据

    public void commit(ActionEvent event) {
        try {
            // 验证输入
            if (!validateInputs()) {
                return;
            }

            // 创建精确AQI数据
            AccurateAqiData accurateAqiData = AccurateAqiDataFactory.getAccurateAqiData(
                    Double.parseDouble(coField.getText()),
                    Double.parseDouble(pm25Field.getText()),
                    Double.parseDouble(so2Field.getText())
            );

            // 创建统计数据
            StatisticData statisticData = DataGenerator.createStatisticData(
                    selectedRowAqiData, accurateAqiData
            );

            // 保存数据
            statisticDataList.add(statisticData);
            MyUtils.writeArrayListToFile("group/data/statistic_data_arraylist.dat", statisticDataList);

            // 显示成功消息并导航
            MyUtils.showAlert("提示", "提交成功", "测量数据已成功保存", Alert.AlertType.INFORMATION);
            DataDetectionController.setIsCommit(true);
            MyUtils.navigateToView(event, "group/nepg/view/DataDetectionView.fxml");

        } catch (NumberFormatException e) {
            MyUtils.showAlert("错误", "输入格式错误", "请输入有效的数值", Alert.AlertType.ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            MyUtils.showAlert("错误", "提交失败", "保存测量数据时发生错误", Alert.AlertType.ERROR);
        }
    }


    //验证输入字段是否完整

    private boolean validateInputs() {
        if (coField.getText().trim().isEmpty() ||
                pm25Field.getText().trim().isEmpty() ||
                so2Field.getText().trim().isEmpty()) {

            MyUtils.showAlert("提示", "输入不完整", "请填写所有测量数据", Alert.AlertType.WARNING);
            return false;
        }

        return true;
    }


    // 显示错误并返回登录页面

    private void showErrorAndExit(String title, String message) {
        MyUtils.showAlert("错误", title, message, Alert.AlertType.ERROR);
        MyUtils.navigateToView(null, "group/nepg/common/view/login.fxml");
    }


    //返回列表页面

    public void returnToLogin(ActionEvent event) {MyUtils.navigateToView(event, "group/nepg/view/DataDetectionView.fxml");}}

